package com.cyz.mobile;


import java.util.Collection;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cyz.service.CouponService;
import com.cyz.service.UserCouponService;
import com.demo.annotation.LoginFilter;
import com.demo.annotation.MobileMethod;
import com.demo.mobile.MobException;
import com.demo.mobile.MobileInfo;
import com.demo.util.DateUtil;
import com.demo.util.MathUtil;
import com.demo.util.ProperityUtil;
import com.demo.util.StringUtil;
import com.demo.validator.MobileLoginValidate;
import com.shopcart.domain.Order;
import com.shopcart.domain.QuickShopping;
import com.shopcart.domain.Store;
import com.shopcart.domain.StoreComment;
import com.shopcart.domain.StoreGoods;
import com.shopcart.domain.StoreGoodsCategory;
import com.shopcart.domain.StorePhoto;
import com.shopcart.service.OrderService;
import com.shopcart.service.QuickShoppingService;
import com.shopcart.service.StoreCommentService;
import com.shopcart.service.StoreGoodsCategoryService;
import com.vsd.domain.Coupon;
import com.vsd.mobile.error.MEnumError;
import com.vsd.service.StoreGoodsService;
import com.vsd.service.StorePhotoService;
import com.vsd.service.StoreService;
import com.vsd.service.UserCollectService;
import com.zy.order.proto.MSOrder.MCoupon;
import com.zy.order.proto.MSOrder.MCouponList;
import com.zy.store.proto.MOAppStore.MCommentList;
import com.zy.store.proto.MOAppStore.MFoodDetail;
import com.zy.store.proto.MOAppStore.MPhoto;
import com.zy.store.proto.MOAppStore.MPhotoList;
import com.zy.store.proto.MOAppStore.MStore;
import com.zy.store.proto.MOAppStore.MStoreGoodsCate;
import com.zy.store.proto.MOAppStore.MStoreGoodsCateList;
import com.zy.store.proto.MOAppStore.MStoreMiniList;
import com.zy.store.proto.MOAppStore.MTgGoods;
import com.zy.store.proto.MOAppStore.MTgGoodsMini;
import com.zy.store.proto.MOAppStore.MTgGoodsMiniList;
import com.zy.sys.proto.MOCommon.MRet;

@Controller
@RequestMapping("/mobile/")
public class MStoreController {
	
	@Autowired
	CouponService couponService;
	@Autowired
	UserCouponService userCouponService;
	@Autowired
	StoreService storeService;
	@Autowired
	StoreGoodsService storeGoodsService;
	@Autowired
	StoreGoodsCategoryService storeGoodsCategoryService;
	@Autowired
	StoreCommentService storeCommentService;
	@Autowired
	UserCollectService userCollectService;
	@Autowired
	OrderService orderService;
	@Autowired
	StorePhotoService storePhoneService;
	@Autowired
	QuickShoppingService quickShoppingService;
	@Autowired
	ProperityUtil properityUtil;
	
	/**
	@api mSysTicketList mSysTicketList	//系统现金券列表
	@return MCouponList
	*/
	@RequestMapping("/mSysTicketList")
	@MobileMethod(isPage=true)
	public MCouponList.Builder mSysTicketList(MobileInfo mobileInfo,Integer page,Integer limit) throws Exception {
		MCouponList.Builder ret = MCouponList.newBuilder();
		Page<Coupon> list = couponService.findBySourceAndBeginTimeBeforeAndEndTimeAfter(1
				, new Date(), new Date(), new PageRequest(page, limit,new Sort(Direction.DESC, "createTime")));
		for (Coupon c : list) {
			MCoupon.Builder mini = MCoupon.newBuilder();
			mini.setBeginTime(DateUtil.dateToStr(c.getBeginTime(), "yyyy-MM-dd"));
			mini.setEndTime(DateUtil.dateToStr(c.getEndTime(), "yyyy-MM-dd"));
			if(c.getType()==1){
				mini.setInfo("满"+c.getFull()+"可以使用");
			}else{
				mini.setInfo(StringUtil.emptyIfBlank(c.getInfo()));
			}
			mini.setSource(1);
			mini.setValue(c.getValue().toString());
			mini.setId(c.getId());
			ret.addList(mini);
 		}
		return ret;
	}
	

	
	
	/**
	@api mStoreTicketList mStoreTicketList	//商家优惠券列表
	@param required string id
	@return MCouponList
	*/
	@RequestMapping("/mStoreTicketList")
	@MobileMethod(isPage=true)
	public MCouponList.Builder mStoreTicketList(MobileInfo mobileInfo,String id,Integer page,Integer limit) throws Exception {
		MCouponList.Builder ret = MCouponList.newBuilder();
		Page<Coupon> list = couponService.findByStoreIdAndSource(id, 2, new PageRequest(page, limit,new Sort(Direction.DESC, "createTime")));
		for (Coupon c : list) {
			MCoupon.Builder mini = MCoupon.newBuilder();
			mini.setBeginTime(DateUtil.dateToStr(c.getBeginTime(), "yyyy-MM-dd"));
			mini.setEndTime(DateUtil.dateToStr(c.getEndTime(), "yyyy-MM-dd"));
			mini.setInfo("满"+c.getFull()+"可以使用");
			mini.setSource(2);
			mini.setValue(c.getValue().toString());
			ret.addList(mini);
 		}
		return ret;
	}
	
	/**
	@api mGetTicket mGetTicket	//优惠券领取(需要登录)
	@param required string id
	@return MRet
	*/
	@RequestMapping("/mGetTicket")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRet.Builder mGetTicket(MobileInfo mobileInfo,String id) throws Exception {
		return userCouponService.adaptCoupon(id, mobileInfo.getUserid());
	}
	
	  
	/**
	@api mStoreTgGoodsList mStoreTgGoodsList	//商家店内团购商品 
	@param required string id  //商家id
	@return MTgGoodsMiniList
	*/
	@RequestMapping("/mStoreTgGoodsList")
	@MobileMethod
	public MTgGoodsMiniList.Builder MTgGoodsMiniList(MobileInfo mobileInfo,String id) throws Exception {
		if(StringUtils.isBlank(id)) throw new MobException("id");
		Store store = storeService.findById(id);
		if(store==null) throw new MobException(MEnumError.STORE_NOT_FOUND);
		
		MTgGoodsMiniList.Builder ret = MTgGoodsMiniList.newBuilder();
		
		Collection<StoreGoods> list  = storeGoodsService.findByStoreIdAndType(id, 2);
		for (StoreGoods g : list) {
			MTgGoodsMini.Builder mini =MTgGoodsMini.newBuilder();
			mini.setGoodsName(g.getName());
			mini.setImg(g.getImg());
			mini.setPrice(g.getNowPrice().toString());
			mini.setId(g.getId());
			ret.addList(mini);
		}
		return ret;
	}
	
	/**
	@api mStoreGoodsCategory mStoreGoodsCategory	//商家店内分类商品
	@param optional string id //商家id
	@return MStoreGoodsCateList
	*/
	@RequestMapping("/mStoreGoodsCategory")
	@MobileMethod
	public MStoreGoodsCateList.Builder mStoreGoodsCategory(MobileInfo mobileInfo,String id) throws Exception {
		if(StringUtils.isBlank(id)) throw new MobException("id");
		Store store = storeService.findById(id);
		if(store==null) throw new MobException(MEnumError.STORE_NOT_FOUND);
		
		MStoreGoodsCateList.Builder ret = MStoreGoodsCateList.newBuilder();
		//查找分类
		Collection<StoreGoodsCategory> list = storeGoodsCategoryService.findByStoreId(id, new Sort(Direction.DESC, "sort"));
		
		for (StoreGoodsCategory ca : list) {
			MStoreGoodsCate.Builder ms = storeGoodsService.findAppList(id, ca.getId(), ca.getName());
			ret.addList(ms);
		}
		return ret;
	}
	
	/**
	@api mStoreWineGoods mStoreWineGoods	//商家店内酒水
	@param optional string id //商家id
	@return MStoreGoodsCate
	*/
	@RequestMapping("/mStoreWineGoods")
	@MobileMethod
	public MStoreGoodsCate.Builder mStoreWineGoods(MobileInfo mobileInfo,String id) throws Exception {
		if(StringUtils.isBlank(id)) throw new MobException("id");
		Store store = storeService.findById(id);
		if(store==null) throw new MobException(MEnumError.STORE_NOT_FOUND);
		return storeGoodsService.findAppListByType(id, 3);
	}
	
	
	/**
	@api mStoreDetail mStoreDetail	//商家详情
	@param optional string id
	@return MStore
	*/
	@RequestMapping("/mStoreDetail")
	@MobileMethod
	public MStore.Builder mStoreDetail(MobileInfo mobileInfo,String id) throws Exception {
		if(StringUtils.isBlank(id)) throw new MobException("id");
		return storeService.findStoreDetail(id, mobileInfo.getUserid());
	}
	
	 
	/**
	@api mCommentList mCommentList	//商家评论列表(分页)
	@param optional string id //商家id
	@return MCommentList
	*/
	@RequestMapping("/mCommentList")
	@MobileMethod(isPage=true)
	public MCommentList.Builder mCommentList(MobileInfo mobileInfo,String id,Integer page,Integer limit) throws Exception {
		if(StringUtils.isBlank(id)) throw new MobException("id");
		MCommentList.Builder ret = storeCommentService.findByStoreId(id, page, limit);
		int c = storeCommentService.countByStoreId(id);
		ret.setCommentCnt(MathUtil.formatAsComment(c));
		return ret;
	}
	
	/**
	@api mStoreList mStoreList	//商家列表 （分页）
	@param optional string catecode //分类
	@param optional number sort  //排序 1智能排序 2 评分 3距离 4人均（默认1）
	@param optional string lat //维度
	@param optional string lng  //精度
	@return MStoreMiniList
	*/
	@RequestMapping("/mStoreList")
	@MobileMethod(isPage=true)
	public MStoreMiniList.Builder mStoreList(MobileInfo mobileInfo,String catecode,String area,String key,Integer sort,String lat,String lng,Integer page,Integer limit) throws Exception {
		if(sort==null) sort = 1;
		if(StringUtils.isBlank(area)) area = mobileInfo.getAreaCode();
		return storeService.selectAppList(catecode,key, area, lat, lng, page, limit,sort);
	}
	
	
	/**
	@api mTgGoodsDetail mTgGoodsDetail	//团购商品详情
	@param optional string id  //商品id
	@return MTgGoods
	*/
	@RequestMapping("/mTgGoodsDetail")
	@MobileMethod
	public MTgGoods.Builder mTgGoodsDetail(MobileInfo mobileInfo,String id) throws Exception {
		if(StringUtils.isBlank(id)) throw new MobException("id");
		MTgGoods.Builder ret = MTgGoods.newBuilder();
		StoreGoods goods = storeGoodsService.findById(id);
		if(goods==null) throw new MobException(MEnumError.GOODS_NOT_FOUND);
		
		ret.setBeforeBuy(properityUtil.getSelf_url()+"/detail?id="+id+"&type=2");
		ret.setName(goods.getName());
		ret.setImgs(goods.getImgs());
		ret.setOldPrice(goods.getOldPrice().toString());
		ret.setNowPrice(goods.getNowPrice().toString());
		ret.setRemark(properityUtil.getSelf_url()+"/detail?id="+id+"&type=1");
		ret.setStoreId(goods.getStoreId());
		ret.setIsCollect(0);
		ret.setTag(goods.getTags());
		ret.setId(id);
		ret.setMode(goods.getMode());
		if(goods.getMode() == 2){//抢购模式
			QuickShopping quickShopping = quickShoppingService.findById(id);
			if(quickShopping != null && quickShopping.getState() == 3 && quickShopping.getTotal()>0){
				ret.setNowPrice(quickShopping.getPrice().toString());
				ret.setTotal(quickShopping.getTotal());
			}
		}
		
		//是否收藏
		if(StringUtils.isNoneBlank(mobileInfo.getUserid())){
			int c = userCollectService.isCollect(mobileInfo.getUserid(), 1, id);
			if(c>0) ret.setIsCollect(1);
		}
		
		MStore.Builder store = storeService.findStoreDetail(goods.getStoreId(), mobileInfo.getUserid());
		
		
		ret.setStoreName(store.getName());
		ret.setStar(store.getStar());
		ret.setCommentCnt(store.getCommentCnt());
		ret.setAddress(store.getAddress());
		ret.setImg("");
		return ret;
	}
	
	/**
	@api mFoodDetail mFoodDetail	//菜品详情
	@param optional string id  //商品id
	@return MFoodDetail
	*/
	@RequestMapping("/mFoodDetail")
	@MobileMethod
	public MFoodDetail.Builder mFoodDetail(MobileInfo mobileInfo,String id) throws Exception {
		if(StringUtils.isBlank(id)) throw new MobException("id");
		MFoodDetail.Builder ret = MFoodDetail.newBuilder();
		StoreGoods goods = storeGoodsService.findById(id);
		if(goods==null) throw new MobException(MEnumError.GOODS_NOT_FOUND);
		
		ret.setImgs(goods.getImgs());
		ret.setName(goods.getName());
		ret.setNowPrice(goods.getNowPrice().toString());
		ret.setRemark(properityUtil.getSelf_url()+"/detail?id="+id+"&type=1");
		ret.setId(id);
		//月销量
		int sell = orderService.selectGoodsSellCnt(id, DateUtil.getFirstOfMonth()+" 00:00:00", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
		ret.setOldPrice((goods.getSellBase()+sell)+"");
		
		return ret;
	}
	
	/**
	@api mPhotoList mPhotoList	//商家相册
	@param optional string id  //商家id
	@return MPhotoList
	*/
	@RequestMapping("/mPhotoList")
	@MobileMethod
	public MPhotoList.Builder mPhotoList(MobileInfo mobileInfo,String id) throws Exception {
		if(StringUtils.isBlank(id)) throw new MobException("id");
		MPhotoList.Builder ret = MPhotoList.newBuilder();
		Collection<StorePhoto> list = storePhoneService.findByStoreId(id);
		for (StorePhoto s : list) {
			MPhoto.Builder m = MPhoto.newBuilder();
			m.setImg(s.getImg());
			m.setInfo(s.getInfo());
			ret.addList(m);
		}
		return ret;
	}
	
	/**
	@api mComment mComment	//评论
	@param optional string orderId  //订单id
	@param optional number score  //得分
	@param optional string content  //内容
	@param optional string imgs  //图片
	@return MRet
	*/
	@RequestMapping("/mComment")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRet.Builder mComment(MobileInfo mobileInfo,String orderId,Integer score,String content,String imgs) throws Exception {
		if(StringUtils.isBlank(content)) throw new MobException("content");
		if(score==null) throw new MobException("score");
		if(StringUtils.isBlank(orderId)) throw new MobException("orderId");
		
		MRet.Builder ret = MRet.newBuilder();
		//找到该订单
		Order order = orderService.findById(orderId);
		//订单是否已评价
		if(order==null||order.getHasComment()==1||order.getState()!=4){
			throw new MobException(MEnumError.ORDER_CAN_NOT_COMMENT);
		}
		//新增商家评价
		StoreComment comment = new StoreComment();
		comment.setContent(content);
		comment.setCreateTime(new Date());
		comment.setImgs(imgs);
		comment.setOrderId(orderId);
		comment.setScore(score);
		comment.setStoreId(order.getStoreId());
		comment.setUserId(mobileInfo.getUserid());
		comment.setShowName(1);
		storeCommentService.save(comment);
		
		ret.setCode(0);
		return ret;
	}
	
}
